#include "settingwidget.h"
#include "ui_settingwidget.h"
#include "gamemanager.h"
#include "ResourceManger/filemanager.h"
#include <QFileDialog>
#include <QFileInfo>
SettingWidget::SettingWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SettingWidget)
{
    ui->setupUi(this);
    Init();
}

SettingWidget::~SettingWidget()
{
    delete ui;
}

void SettingWidget::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    Refresh();
}

void SettingWidget::Init()
{
    setWindowModality(Qt::ApplicationModal);
    setWindowTitle("设置");
    setWindowIcon(QIcon(":/res/icon/setting.png"));
    setFixedSize(600,450);
    connect(ui->yesBtn,&QPushButton::clicked,this,&SettingWidget::Save);
    connect(ui->iconBtn,&QPushButton::clicked,this,[=](){
        QString path = QFileDialog::getOpenFileName(this, tr("选择图标"), ".", tr("Images (*.png *.jpeg *.jpg)"));
        if(!path.isEmpty() && FileManager::Instance().GetFileType(path) == FileManager::IMAGE)
        {
            iconPath = path;
            ui->iconBtn->setStyleSheet("border-image:url(" + path +");");
        }
    });
    Refresh();
}

void SettingWidget::Refresh()
{
    ui->nameEdit->setText(GameManager::Instance().name);
    ui->bgmPathEdit->setText(GameManager::Instance().bgmPath);
    ui->fullScreen->setChecked(GameManager::Instance().fullScreen);
    iconPath = GameManager::Instance().iconPath;
    if(!iconPath.isEmpty())
    {
        ui->iconBtn->setStyleSheet("border-image:url(" + iconPath +");");
    }
}

void SettingWidget::Save()
{
    GameManager::Instance().name = ui->nameEdit->text();
    GameManager::Instance().fullScreen = ui->fullScreen->isChecked();
    //图标
    QString icon = FileManager::Instance().iconPath;
    if(icon != iconPath && FileManager::Instance().GetFileType(iconPath) == FileManager::IMAGE)
    {
        GameManager::Instance().iconPath = icon;
        FileManager::Instance().DeleteFile(icon);
        FileManager::Instance().CopyFile(iconPath,icon,false);
    }
    //音乐
    QString bgmPath = ui->bgmPathEdit->text();
    QString bgm = FileManager::Instance().bgmPath;
    if(bgm!= bgmPath && FileManager::Instance().GetFileType(bgmPath) == FileManager::SOUND)
    {
        QFileInfo info(bgmPath);
        GameManager::Instance().bgmPath = bgm;
        FileManager::Instance().CopyFile(bgmPath,bgm,false);
    }
    GameManager::Instance().Save();
    emit EventCenter::Instance().ChangeWindowName("MyGame-" + ui->nameEdit->text());
}
